package com.gonsin.license;

import lombok.extern.slf4j.Slf4j;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Map;

@Slf4j
public class Md5Utils {

    private static String string = "abcdefghijklmnopqrstuvwxyz";

    public static String randomStr(){
        return randomStr(16);
    }

    private static int getRandom(int count) {
        return (int) Math.round(Math.random() * (count));
    }

    private static String randomStr(int length){
        StringBuffer sb = new StringBuffer();
        int len = string.length();
        for (int i = 0; i < length; i++) {
            sb.append(string.charAt(getRandom(len-1)));
        }
        return sb.toString();
    }

    public static String string2Unicode(String string) {
        StringBuffer unicode = new StringBuffer();
        for (int i = 0; i < string.length(); i++) {
            char c = string.charAt(i);
            unicode.append("u" + Integer.toHexString(c));
        }
        return unicode.toString();
    }

    public static String unicode2String(String unicode) {

        StringBuffer string = new StringBuffer();
        String[] hex = unicode.split("u");

        for (int i = 1; i < hex.length; i++) {
            int data = Integer.parseInt(hex[i], 16);
            string.append((char) data);
        }

        return string.toString();
    }


    public static String mapToString(Map<String, String[]> paramters){
        StringBuffer sb = new StringBuffer();
        Iterator<Map.Entry<String, String[]>> iterable = paramters.entrySet().iterator();
        sb.append("[");
        while(iterable.hasNext()){
            Map.Entry<String, String[]> entry = iterable.next();
            sb.append(entry.getKey())
                    .append("=")
                    .append(Arrays.toString(entry.getValue()));
            if(iterable.hasNext()){
                sb.append("; ");
            }
        }
        sb.append("]");
        return sb.toString();
    }

    public static String getMD5(String src) {
        byte[] defaultBytes = src.getBytes();
        StringBuffer hexString = new StringBuffer();
        try {
            MessageDigest algorithm = MessageDigest.getInstance("MD5");
            algorithm.reset();
            algorithm.update(defaultBytes);
            byte messageDigest[] = algorithm.digest();

            for (int i = 0; i < messageDigest.length; i++) {
                String hex = Integer.toHexString(0xFF & messageDigest[i]);
                if(hex.length() == 1){
                    hex = "0" + hex;
                }
                hexString.append(hex);
            }
        } catch (NoSuchAlgorithmException e) {
            log.error(e.toString(), e);
        }
        return hexString.toString();
    }
}
